package java高并发核心编程.线程池;

import java.lang.annotation.Target;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

//一个简单的线程工厂
public class SimpleThreadFactory implements ThreadFactory {

    static AtomicInteger threadNo = new AtomicInteger(1);

    @Override
    public Thread newThread(Runnable target) {
        String threadName = "simpleThread-" + threadNo.get();
        System.out.println("创建一个线程，名称为：" + threadName);
        threadNo.incrementAndGet();
        //设置线程名称和异步执行目标
        Thread thread = new Thread(target, threadName);
        //设置为守护线程
        thread.setDaemon(true);
        return thread;
    }

    static class TargetTask implements Runnable {
        static AtomicInteger taskNo = new AtomicInteger(1);
        private String taskName;

        public TargetTask() {
            taskName = "task-" + taskNo.get();
            taskNo.incrementAndGet();
        }

        @Override
        public void run() {
            System.out.println("任务：" + taskName + " doing");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(taskName + "运行结束.");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //使用自定义线程工厂快捷创建一个固定大小的线程池
        ExecutorService pool = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
        for (int i = 0; i < 5; i++) {
            pool.submit(new TargetTask());
        }
        //等待10秒
        Thread.sleep(10000);
        System.out.println("关闭线程池");
        pool.shutdown();
    }
}
